﻿using System;
using System.Collections.Generic;
using System.Text;
using GlTool.GlHttp;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Net;
using System.Web;
using System.IO;
using GL.Tools;
using System.Drawing.Drawing2D;
using System.Linq;
using WAD.DAL;
using WAD.Model;
using NSoup.Nodes;
using NSoup;
using WAD.WEB.AppCode.Html;

namespace WAD.WEB.AppCode
{

    /// <summary>
    /// 网络请求类
    /// </summary>
    public class HttpTool
    {
        /// <summary>
        /// PC端电脑浏览器标识
        /// </summary>
        private const String PC_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36";

        /// <summary>
        /// 移动端浏览器标识
        /// </summary>
        public const String MOBILE_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1";

        /// <summary>
        /// Get方式获取网络数据
        /// </summary>
        /// <param name="url">网络链接</param>
        /// <returns></returns>
        public static String GetHttpString(String url)
        {
            return GetHttpString(url, false, false,Encoding.UTF8);
        }

        /// <summary>
        /// Get方式获取网络数据
        /// </summary>
        /// <param name="url">网络链接</param>
        /// <param name="isMobile">是否模拟手机提交</param>
        /// <returns></returns>

        public static String GetHttpString(String url, bool isMobile)
        {
            return GetHttpString(url, false, isMobile,Encoding.UTF8);
        }
        public static String GetHttpString(String url,Encoding coding, bool isMobile)
        {
            return GetHttpString(url, false, isMobile,coding);
        }
        public static String GetHttpString(String url, bool isPost, bool isMobile, out string returnUrl)
        {
            returnUrl = url;
            String html = string.Empty;
            //是否模拟手机请求
            if (isMobile)
                QD.Utils.WebHttpHelper.UserAgent = MOBILE_USER_AGENT;
            else
                QD.Utils.WebHttpHelper.UserAgent = PC_USER_AGENT;

            if (isPost)
                html = QD.Utils.WebHttpHelper.Request(url, "", "POST", Encoding.UTF8, out returnUrl);
            else
                html = QD.Utils.WebHttpHelper.Request(url, "", "GET", Encoding.UTF8, out returnUrl);

            return html;
        }

        /// <summary>
        /// 获取网络数据
        /// </summary>
        /// <param name="url">网络链接</param>
        /// <param name="method">请求方式</param>
        /// <returns></returns>
        public static String GetHttpString(String url, bool isPost, bool isMobile,Encoding coding)
        {
            //GlHttpBase http = null;

            ////是否post请求
            //if (isPost)
            //{
            //    http = new GlHttpPost(url);
            //}
            //else
            //{
            //    http = new GlHttpGet(url);
            //}

            ////是否模拟手机请求
            //if (isMobile)
            //{
            //    http.setHead("User-Agent", MOBILE_USER_AGENT);
            //}
            //else
            //{
            //    http.setHead("User-Agent", PC_USER_AGENT);
            //}

            //QD.Utils.WebHttpHelper.Request(url);

            //GlHttpResponse response = http.Execute();
            //String html = response.ToString();
            //response.Close();



            //是否模拟手机请求
            if (isMobile)
            {
                QD.Utils.WebHttpHelper.UserAgent = MOBILE_USER_AGENT;
            }
            else
            {
                QD.Utils.WebHttpHelper.UserAgent = PC_USER_AGENT;
            }
            if (coding == null)
                coding = Encoding.UTF8;
            String html = string.Empty;
            if (isPost)
                html = QD.Utils.WebHttpHelper.Request(url, "", "POST", coding);
            else
                html = QD.Utils.WebHttpHelper.Request(url, "", "GET", coding);

            return html;
        }

        public static Bitmap Get_img(string url)
        {
            Bitmap img = null;
            HttpWebRequest req;
            HttpWebResponse res = null;
            try
            {
                System.Uri httpUrl = new System.Uri(url);
                req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                req.Timeout = 180000; //设置超时值10秒
                req.UserAgent = PC_USER_AGENT;
                req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                req.Method = "GET";
                res = (HttpWebResponse)(req.GetResponse());
                img = new Bitmap(res.GetResponseStream());//获取图片流                 
                // img.Save(@"E:/" + DateTime.Now.ToFileTime().ToString() + ".png");//随机名
            }

            catch (Exception ex)
            {
                string aa = ex.Message;
            }
            finally
            {
                res.Close();
            }
            return img;
        }

        public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);

                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();

                return b;
            }
            catch
            {
                return null;
            }
        }


        /// <summary>
        /// 显示微信图片(解决防盗链问题)
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string FormatImg(string html)
        {
            if (string.IsNullOrEmpty(html) || html.IndexOf("mmbiz.qpic.cn") == -1)
                return html;

            html = html.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("\t", "");
            Regex res = new Regex("<img([\\s\\S].*?)>", RegexOptions.IgnoreCase);

            if (!res.IsMatch(html))
                return html;

            Regex reimg = new Regex("src=\"([\\s\\S].*?)\"", RegexOptions.IgnoreCase);
            MatchCollection list = res.Matches(html);
            MatchCollection lists = res.Matches(html);
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Groups[1].Value.IndexOf("mmbiz.qpic.cn") == -1)
                    continue;
                try
                {
                    string src = reimg.Match(list[i].Groups[1].Value).Groups[1].Value;
                    html = html.Replace(lists[i].Value, string.Format("<script>showImg('{0}');</script>", reimg.Match(list[i].Groups[1].Value).Groups[1].Value));
                }
                catch (Exception ex) { }
            }
            return html;
        }

        /// <summary>
        /// 获取并保存源码
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Dictionary<string, object> GetSavaSource(String url, bool isReturnId, bool isSave)
        {
            String md5 = StringHelper.MD5Encrypt(url);
            Dictionary<string, object> model = DaoUrlSource.GetHtml(md5, isReturnId);

            if (model == null)
            {
                model = new Dictionary<string, object>();
                string returnUrl = "";

                if (url.IndexOf("toutiao.com") != -1 || url.IndexOf("pstatp.com") != -1)           //今日头条处理
                {
                    model["source"] = HtmlFomat.FomartToutiao(HttpTool.GetHttpString(url, false, true, out returnUrl));
                    if (returnUrl.IndexOf("365yg.com") > -1)
                    {
                        return null;
                    }
                }
                else if (url.IndexOf("://xw.qq.com") > -1)      //微信链接处理
                {
                    model["source"] = HtmlFomat.FomartXwqq(HttpTool.GetHttpString(url, true));
                }
                else if (url.IndexOf("v.qq.com") != -1)           //腾讯视频处理
                {
                    model["source"] = HttpTool.GetHttpString(url, false, true, out returnUrl);
                }
                else if (url.IndexOf("http://url.cn/") > -1)    //url.cn短域名解析
                {
                    model["source"] = HttpTool.GetHttpString(url, false, true, out returnUrl);
                    //短域名是toutiao.com，则格式化内容
                    if (returnUrl.IndexOf("toutiao.com") > -1)
                        model["source"] = HtmlFomat.FomartToutiao(Convert.ToString(model["source"]));
                }else if (url.IndexOf("mp.weixin.qq.com") > -1)
                {
                    model["source"] = HtmlFomat.FormatWeiXin(HttpTool.GetHttpString(url, true));
                }else if (url.IndexOf("tv.sohu.com", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    model["source"] = HttpTool.GetHttpString(url, Encoding.GetEncoding("GB2312"), true);
                }
                else
                {
                    model["source"] = HttpTool.GetHttpString(url, true);
                }

                model["url"] = url;
                model["return_url"] = returnUrl;
                model["id"] = 0;
                //记录网址和HTML内容
                if (isSave)
                {
                    MUrlSource m = new MUrlSource() { md5 = md5, source = Convert.ToString(model["source"]), url = url, return_url = returnUrl };
                    model["id"] = DaoUrlSource.Add(m);
                }
            }
            return model;
        }

        //获取并保存源码
        public static String GetAndSavaSource(String url, bool isReturnId, bool isSave)
        {
            String md5 = StringHelper.MD5Encrypt(url);
            String html = DaoUrlSource.GetHtml(md5);

            if (html != null)
                return html;

            //处理今日头条源码
            if (url.IndexOf("toutiao.com") != -1 || url.IndexOf("pstatp.com") != -1)
            {
                html = HtmlFomat.FomartToutiao(HttpTool.GetHttpString(url, true));
            }
            else if (url.IndexOf("://xw.qq.com") > -1)
            {
                html = HttpTool.GetHttpString(url, true).Replace("top.location = self.location", "");
            }
            else
                html = HtmlFomat.FormatWeiXin(HttpTool.GetHttpString(url, true));

            //记录网址和HTML内容
            if (isSave)
            {
                MUrlSource m = new MUrlSource() { md5 = md5, source = html, url = url, return_url = "" };
                DaoUrlSource.Add(m);
            }
            return html;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool SavaFile(String url, String fileName)
        {
            GlHttpBase http = new GlHttpGet(url);
            http.Timeout = 20000;   //20秒
            GlHttpResponse response = http.Execute();
            
            FileInfo fi = new FileInfo(fileName);

            //文件夹不存在创建文件夹
            if (!Directory.Exists(fi.DirectoryName))
            {
                Directory.CreateDirectory(fi.DirectoryName);
            }

            bool flag = response.savaFile(fileName);
            response.Close();
            http = null;
            return flag;
        }

    }
}
